package com.linewell.system.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.linewell.system.model.SysDepartment;
import com.linewell.system.pagemodel.DepartmentTreeNode;

/**
 * 功能说明：把通过SQL语句获取的数据，通过遍历进行填充
 */
public class DepartmentTreeUtil {
	private List<SysDepartment> lstAll;

	public List<SysDepartment> getLstAll() {
		return lstAll;
	}

	public void setLstAll(List<SysDepartment> lstAll) {
		this.lstAll = lstAll;
	}

	public List<DepartmentTreeNode> findById(Integer parentId) {
		List<DepartmentTreeNode> subs = new ArrayList<DepartmentTreeNode>();
		for (int i = 0; i < lstAll.size(); i++) {
			DepartmentTreeNode mod = recordToTreeNode((SysDepartment) lstAll.get(i));
			if (parentId == null) {
				if (mod.getDepPid() == null || mod.getDepPid() == 0) {
					lstAll.remove(i);
					i--;
					List<DepartmentTreeNode> modSubs = findById(mod.getId());
					if (modSubs.size() > 0) {
						mod.setChildren(modSubs);
					}
					subs.add(mod);
				}
				
			} else {
				if (mod.getDepPid() != null && mod.getDepPid().intValue() == parentId.intValue()) {
					List<DepartmentTreeNode> modSubs = findById(mod.getId());
					if (modSubs.size() > 0) {
						mod.setChildren(modSubs);
					}
					subs.add(mod);
				}
			}
		}
		return subs;
	}

	private DepartmentTreeNode recordToTreeNode(SysDepartment record) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DepartmentTreeNode td = new DepartmentTreeNode();
		td.setId(record.getDepId());
		td.setText(record.getDepName());
		if (record.getDepPId() != null)
			td.setDepPid(record.getDepPId());
		if (record.getAddress() != null)
			td.setAddress(record.getAddress());
		if (record.getX() != null)
			td.setX(record.getX());
		if (record.getY() != null)
			td.setY(record.getY());
		if (record.getPhone() != null)
			td.setPhone(record.getPhone());
		// if(record.getStr("LEADER_NAME") != null)
		// td.setLeaderName(record.getStr("LEADER_NAME"));
		if (record.getIcon() != null)
			td.setIcon(record.getIcon());
		if (record.getSort() != null)
			td.setSort(record.getSort());
		if (record.getDesction() != null)
			td.setDesction(record.getDesction());
		// if(record.getCreateUserId() != null)
		// td.setCreator(record.getCreateUserId());
		if (record.getCreateTime() != null)
			td.setCreateTime(sdf.format(record.getCreateTime()));
		// if(record.getStr("EDITOR") != null)
		// td.setEditor(record.getStr("EDITOR"));
		if (record.getUpdateTime() != null)
			td.setEditTime(sdf.format(record.getUpdateTime()));
		if (record.getStatus() != null)
			td.setStatus(record.getStatus().byteValue());
		if (record.getDepType() != null)
			td.setDepType(record.getDepType().byteValue());


		return td;
	}

}
